{% extends 'base.html' %}
{% load static %}
{% load django_bootstrap5 %}

{% block title %}登录 - 商城系统{% endblock %}

{% block extra_css %}
<style>
    .login-container {
        max-width: 450px;
        margin: 2rem auto;
    }
    
    .login-header {
        text-align: center;
        margin-bottom: 2rem;
    }
    
    .login-card {
        border-radius: 10px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    }
    
    .login-form {
        padding: 1.5rem;
    }
    
    .social-login {
        display: flex;
        justify-content: center;
        margin-top: 1.5rem;
    }
    
    .social-btn {
        margin: 0 0.5rem;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        text-decoration: none;
        transition: transform 0.3s ease;
    }
    
    .social-btn:hover {
        transform: translateY(-3px);
    }
    
    .btn-weixin {
        background-color: #07C160;
    }
    
    .btn-qq {
        background-color: #12B7F5;
    }
    
    .btn-weibo {
        background-color: #E6162D;
    }
    
    .loading {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(0, 123, 255, 0.3);
        border-radius: 50%;
        border-top-color: #007bff;
        animation: spin 1s ease-in-out infinite;
        margin-right: 10px;
        vertical-align: middle;
    }
    
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
    
    .field-error {
        color: #dc3545;
        font-size: 0.875rem;
        margin-top: 0.25rem;
    }
    
    .feedback-message {
        display: none;
        padding: 10px;
        margin-bottom: 15px;
        border-radius: 5px;
    }
    
    .feedback-message.success {
        display: block;
        background-color: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
    }
    
    .feedback-message.error {
        display: block;
        background-color: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
    }
    
    .password-toggle {
        cursor: pointer;
        color: #6c757d;
    }
    
    .password-toggle:hover {
        color: #495057;
    }
</style>
{% endblock %}

{% block content %}
<div class="login-container">
    <div class="login-header">
        <h1>用户登录</h1>
        <p class="text-muted">欢迎回来，请登录您的账户</p>
    </div>
    
    <div class="card login-card">
        <div class="login-form">
            <div id="feedback-message" class="feedback-message"></div>
            
            <form method="post" id="login-form" action="{% url 'login' %}{% if request.GET.next %}?next={{ request.GET.next }}{% endif %}">
                {% csrf_token %}
                
                {% if request.GET.next %}
                <input type="hidden" name="next_url" value="{{ request.GET.next }}">
                {% endif %}
                
                {% if form.errors %}
                <div class="alert alert-danger">
                    用户名或密码错误，请重新输入。
                </div>
                {% endif %}
                
                <div class="mb-3">
                    <label for="id_username" class="form-label">用户名或邮箱</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-person"></i></span>
                        <input type="text" name="username" id="id_username" class="form-control" placeholder="请输入用户名或邮箱" required>
                    </div>
                    <div class="field-error" id="username-error"></div>
                </div>
                
                <div class="mb-3">
                    <label for="id_password" class="form-label">密码</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-lock"></i></span>
                        <input type="password" name="password" id="id_password" class="form-control" placeholder="请输入密码" required>
                        <span class="input-group-text password-toggle" id="password-toggle">
                            <i class="bi bi-eye"></i>
                        </span>
                    </div>
                    <div class="field-error" id="password-error"></div>
                </div>
                
                <div class="mb-3 form-check">
                    <input type="checkbox" name="remember_me" id="id_remember_me" class="form-check-input">
                    <label for="id_remember_me" class="form-check-label">记住我</label>
                </div>
                
                <div class="d-grid gap-2">
                    <button type="submit" class="btn btn-primary" id="login-btn">
                        <span id="login-loading" class="loading d-none"></span>
                        <span id="login-text">登录</span>
                    </button>
                </div>
                
                <div class="mt-3 text-center">
                    <a href="{% url 'forgot_password' %}?next={{ request.META.HTTP_REFERER|default:request.build_absolute_uri }}" class="text-decoration-none">忘记密码？</a>
                </div>
                
                <hr>
                
                <div class="text-center">
                    <p>还没有账户？ <a href="{% url 'register' %}{% if request.GET.next %}?next={{ request.GET.next }}{% endif %}" class="text-decoration-none">立即注册</a></p>
                </div>
                
{#                <div class="social-login">#}
{#                    <a href="#" class="social-btn btn-weixin" title="微信登录">#}
{#                        <i class="bi bi-wechat"></i>#}
{#                    </a>#}
{#                    <a href="#" class="social-btn btn-qq" title="QQ登录">#}
{#                        <i class="bi bi-chat-fill"></i>#}
{#                    </a>#}
{#                    <a href="#" class="social-btn btn-weibo" title="微博登录">#}
{#                        <i class="bi bi-sina-weibo"></i>#}
{#                    </a>#}
{#                </div>#}
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const loginForm = document.getElementById('login-form');
        const loginBtn = document.getElementById('login-btn');
        const loginLoading = document.getElementById('login-loading');
        const loginText = document.getElementById('login-text');
        const feedbackMessage = document.getElementById('feedback-message');
        const passwordToggle = document.getElementById('password-toggle');
        const passwordInput = document.getElementById('id_password');
        
        // 保存当前页面URL作为referer
        function saveCurrentUrlAsReferer() {
            // 不保存登录和注册页面
            if (!window.location.pathname.includes('login') && 
                !window.location.pathname.includes('register')) {
                localStorage.setItem('refererUrl', window.location.href);
            }
        }
        
        // 获取来源URL
        function getRefererUrl() {
            // 首先尝试从URL参数获取
            const urlParams = new URLSearchParams(window.location.search);
            const nextUrl = urlParams.get('next');
            if (nextUrl) {
                return nextUrl;
            }
            
            // 尝试从localStorage获取
            const refererUrl = localStorage.getItem('refererUrl');
            return refererUrl;
        }
        
        // 在页面加载时保存来源URL
        saveCurrentUrlAsReferer();
        
        // 密码显示/隐藏切换
        passwordToggle.addEventListener('click', function() {
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
            
            // 更改图标
            const icon = passwordToggle.querySelector('i');
            if (type === 'password') {
                icon.classList.remove('bi-eye-slash');
                icon.classList.add('bi-eye');
            } else {
                icon.classList.remove('bi-eye');
                icon.classList.add('bi-eye-slash');
            }
        });
        
        // 设置按钮加载状态
        function setButtonLoading(isLoading) {
            if (isLoading) {
                loginBtn.disabled = true;
                loginLoading.classList.remove('d-none');
                loginText.textContent = '登录中...';
            } else {
                loginBtn.disabled = false;
                loginLoading.classList.add('d-none');
                loginText.textContent = '登录';
            }
        }
        
        // 显示反馈消息
        function showFeedback(message, isSuccess) {
            feedbackMessage.textContent = message;
            feedbackMessage.className = isSuccess ? 
                'feedback-message success' : 
                'feedback-message error';
        }
        
        // 清除错误信息
        function clearErrors() {
            document.querySelectorAll('.field-error').forEach(el => {
                el.textContent = '';
            });
            feedbackMessage.textContent = '';
            feedbackMessage.className = 'feedback-message';
        }
        
        // 表单验证
        function validateForm() {
            clearErrors();
            
            const username = document.getElementById('id_username').value;
            const password = document.getElementById('id_password').value;
            
            let isValid = true;
            
            if (!username) {
                document.getElementById('username-error').textContent = '请输入用户名或邮箱';
                isValid = false;
            }
            
            if (!password) {
                document.getElementById('password-error').textContent = '请输入密码';
                isValid = false;
            }
            
            return isValid;
        }
        
        // 表单提交
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (!validateForm()) {
                return;
            }
            
            setButtonLoading(true);
            
            // 获取表单数据
            const formData = new FormData(loginForm);
            
            // 添加referer URL
            const refererUrl = getRefererUrl();
            if (refererUrl) {
                formData.append('next_url', refererUrl);
            }
            
            // 发送AJAX请求
            fetch('{% url "login" %}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                // 检查响应状态
                if (response.redirected) {
                    // 登录成功，重定向到指定页面
                    window.location.href = response.url;
                    return;
                }
                
                // 如果没有重定向，尝试解析JSON响应
                return response.json().catch(() => {
                    // 如果不是JSON，返回原始响应
                    return response;
                });
            })
            .then(data => {
                // 如果是JSON响应
                if (data && typeof data === 'object') {
                    if (data.success) {
                        // 登录成功，重定向到指定页面
                        window.location.href = data.redirect_url || refererUrl || '{% url "index" %}';
                    } else {
                        // 登录失败，显示错误信息
                        setButtonLoading(false);
                        
                        if (data.errors) {
                            // 显示字段错误
                            for (const field in data.errors) {
                                const errorElement = document.getElementById(`${field}-error`);
                                if (errorElement) {
                                    errorElement.textContent = data.errors[field].join(' ');
                                }
                            }
                        } else {
                            // 显示一般错误信息
                            showFeedback(data.message || '用户名或密码错误，请重新输入', false);
                        }
                    }
                } else {
                    // 如果不是预期的JSON响应，回退到传统表单提交
                    loginForm.submit();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                setButtonLoading(false);
                showFeedback('登录过程中出现错误，请稍后重试', false);
            });
        });
    });
</script>
{% endblock %}